package com.android.geotrack.connection;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class HttpClientHelper
{
	/**
	* Performs a get request with the Apache HttpClient component.
	*
	* @param url Url to perform the request on.
	* @return The Http response or null, if an error occurred.
	*/
	public String performGetRequest (String url)
	{
		String result = null;
		
		// Create an instance of HttpClient.
		HttpClient httpclient = new DefaultHttpClient();
		
		// Create a method instance.
		HttpGet httpget = new HttpGet(url);
		Log.v("HTTP Client", "Executing request " + httpget.getURI());
		
		// Create a response handler
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		
		try {
		
			// Execute the request and recieve the response.
			result = httpclient.execute(httpget, responseHandler);
			
			// If you need some more informations about the connection e.g.
			// the status code, you can work with HttpResponse and do stuff
			// like that:
			
			// HttpResponse response = httpclient.execute(httpget);
			// int statuscode = response.getStatusLine().getStatusCode();
			// Log.v("Demo", "Request executed. Result: " + statuscode);
			//
			// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			// StringBuilder stringBuilder = new StringBuilder();
			// String line = null;
			//
			// while ((line = bufferedReader.readLine()) != null) {
			// stringBuilder.append(line + "\n");
			// }
			//
			// bufferedReader.close();
			// result = stringBuilder.toString();
		
		} catch (ClientProtocolException e) {
			Log.v("HTTP Client", "ClientProtocolException " + e.toString());
			result = null;
		} catch (IOException e) {
			Log.v("HTTP Client", "IOException " + e.toString());
			result = null;
		}
		
		// Shut down the connection manager to ensure
		// immediate deallocation of all system resources
		httpclient.getConnectionManager().shutdown();
		
		return result;
	}
}